<template>
  <div class="yy-page yy-system-template_list">

    <div class="yy-page-search" v-if="showSearch">
      <WidgetForm ref="searchFormWidget" :option="{
        style: 'display: flex;',
        itemStyle: 'margin-right: 10px;margin-bottom: 0;align-items: center;'
      }" :form-fields="search.formFields" :form-buttons="search.formButtons" />

      <div class="yy-page-search_actions">
        <el-button type="info">导出</el-button>
      </div>
    </div>
    <div class="yy-page-data">
      <WidgetTable
          ref="tableDataRef"
          :is-loading="table.isLoading"
          :columns="table.columns"
          :data="table.data"
          :options="table.options"
          :formats="table.formats"
          :paging-data="table.paging"
      >
        <template v-slot:auditStatus="{row, column}">
          <el-text type="danger">待审批</el-text>
        </template>
      </WidgetTable>
    </div>
    <WidgetFormDialog ref="widgetFormDialogRef"
                      :form-fields="dialog.formFields"
                      :model-instance="dialog.modelInstance"
                      :save-api-fun="dialog.saveApiFun"
                      :update-api-fun="dialog.updateApiFun"
                      :option="{
                      closeOnClickModal: true,
                      businessName: '模板',
                    }"
                      @edit-callback="onEditCallback"
    />
  </div>
</template>

<script setup lang="ts">
import {onBeforeMount, defineEmits, reactive, ref} from "vue";
import {formatDate} from "@/utils";
import {ElButton, ElMessage} from "element-plus";
import WidgetTable from "@/components/widget/WidgetTable.vue";
import TemplateApi from "@/api/broadcast/template";
import {BcTemplateModel} from "@/model/BcTemplateModel";
import {useRouter} from "vue-router";
import WidgetFormDialog from "@/components/widget/WidgetFormDialog.vue";
import ResourceApi from "@/api/broadcast/resource";
import WidgetForm from "@/components/widget/WidgetForm.vue";
import {WidgetFormField} from "@/model/Definition";
import {BaseModel} from "@/model/BaseModel";
import {EmployeeModel} from "@/model/EmployeeModel";
import EmployeeApi from "@/api/system/empl";

const router = useRouter()
const $emit = defineEmits({
  //
})
const showSearch = ref(true)
const search = reactive<{formFields: WidgetFormField[],formData: any, formButtons: any, modelInstance: BaseModel, searchApiFun:any}>({
  modelInstance: new EmployeeModel(),
  searchApiFun: EmployeeApi.listEmployee,
  formData: {},
  formFields: [
    {field: 'searchKey', config: {input: {clearable: true}}, placeholder:"请输入名称或编码的关键字", label: '关键字', type: 'text', style:'width: 200px;',},
    {field: 'deptId', config:{select: {clearable: true}}, label: '科室', type: 'select', initVal: -1, style:'width: 100px;', options: [
        {label: '全部', value: -1}, {label: '内科', value: 1}, {label: '肝胆外科', value: 2}, {label: '脑病科', value: 3}, {label:'普外科', value: 4}
    ]},
    {field: 'timeRange', type: 'dateRange', initVal: [new Date(2023, 6, 1).getTime(),new Date(2024, 5, 23).getTime()]}
  ],
  formButtons: [
    {type: 'primary', label:'搜索', icon: 'search', atClick: ()=> {
        const formData = searchFormWidget.value.getFormFieldValue()
        search.formData = Object.assign({}, formData, {searchKey: formData.searchKey?.length ? formData.searchKey : null, state: formData.state === -1 ? null : formData.state})
        getList()
      }
    },
    {type: 'default', label: '清空', icon: 'refresh', atClick: () => {
        searchFormWidget.value.resetFields()
      }
    }
  ]
})

const loading = ref(false)
const dialog = reactive({
  modelInstance: new BcTemplateModel(),
  saveApiFun: TemplateApi.saveTempalte,
  updateApiFun: TemplateApi.updateTemplate,
  formFields: [
    {field: 'name', label: '模板名称', type: 'text', placeholder: '请输入设备名称', required: [{required: true, message: '名称不能为空', trigger: 'blur'}]},
    {field: 'description', label: '描述', type: 'textarea'},
  ]
})

const table = reactive({
  isLoading: false,
  columns: [
    {
      "field":"index",
      "label":"序号",
      "type": "index",
      "showable":true,
      "fixed": 'left',
      "align": 'center',
      "width": 60
    },
    {
      "field":"name",
      "label":"姓名",
      "showable":true,
      "fixed": 'left',
    },
    {
      "field":"id",
      "label":"工号",
      "showable":true,
    }
  ],
  paging: {
    isPaging: true,
    pageSize: 50,
    pageIndex: 1,
    total: 113,
    pageChange: (pageIndex: number) => {
      onPageChange(pageIndex)
    }
  },
  options: {
    highlight: true
  },
  data: [],
  formats: {
  }
})

const searchFormWidget = ref()
const tableDataRef = ref()
const widgetFormDialogRef = ref()

onBeforeMount(() => {
  getList()
})

const onShowSearch = () => {
  showSearch.value = !showSearch.value
  tableDataRef.value.onWindowResize()
}

const onCopyTemplate = async (temp) => {
   TemplateApi.copyTemplate(temp.id).then((res) => {
       const index = table.data.findIndex(item => item.id === temp.id)
       if (index >= 0) {
           table.data.splice(index, 0, res)
       }
       ElMessage.success({
           message: '拷贝模板成功',
           showClose: true
       })
   })
}

const handleCreate = async (temp) => {
  if (loading.value) {
    return false
  }
  loading.value = true
  await router.push({
    name: 'TemplateCreate',
    params: {
      tempId: temp.id
    }
  })
}

const getList = (pageIndex: number = 1) => {
  table.isLoading = true
  const doctorList = [
      {name: '许*敏', id: 'xm'},
      {name: '沈*挺', id: '1006'},
      {name: '童*慧', id: '1007'},
      {name: '沈*', id: '1008'},
      {name: '冷*丰', id: '1009'},
      {name: '吴*晨', id: '1010'},
      {name: '蒋*鲸', id: '1011'},
      {name: '罗*文', id: '1012'},
      {name: '宋*飞', id: '1013'},
      {name: '李*应', id: '1014'},
      {name: '宋*斌', id: '1015'},
      {name: '李*婷', id: '1016'},
      {name: '王*慧', id: '1017'},
      {name: '高*', id: '1018'},
      {name: '李*强', id: '1019'},
      {name: '黄*迎', id: '1020'},
      {name: '王*利', id: '1021'},
      {name: '张*华', id: '1022'},
      {name: '曾*强', id: '1023'},
      {name: '武*', id: '1024'}
  ]

  const data = []
  const months = getLastYearMonths()
  for (let j = 0; j < months.length; j++) {
    table.columns.push({
      field: months[j],
      label: months[j],
      "showable":true
    })
  }
  for (let i = 0; i < 20; i++) {
    const doctor = doctorList[i % doctorList.length];
    const obj = {...doctor}
    for (let j = 0; j < months.length; j ++) {
      obj[months[j]] =  Math.ceil(Math.random() * 5)
    }
    data.push(obj)
  }
  setTimeout(() => {

    table.data = data

    table.isLoading = false
  }, 1000)
}

const  getLastYearMonths = () => {
  // 获取当前日期
  const now = new Date();

  // 创建一个数组来存储月份
  const months = [];

  // 遍历近一年的月份
  for (let i = 0; i < 12; i++) {
    // 创建一个新的日期对象，设置为当前月份减i
    const monthDate = new Date(now.getFullYear(), now.getMonth() - i, 1);

    // 如果月份小于0，则需要调整年份（因为JavaScript的月份是从0开始的）
    if (monthDate.getMonth() < 0) {
      monthDate.setFullYear(monthDate.getFullYear() - 1);
      monthDate.setMonth(11 + monthDate.getMonth()); // 加上上个月的月数，使其回到上一年的最后一个月
    }

    // 将月份添加到数组中，这里使用数组的push方法
    // 可以选择只存储月份数字（0-11），或者存储格式化的字符串（如 "2023-09"）
    months.push(
        // 如果你只需要月份和年份，可以这样做：
        `${monthDate.getFullYear()}-${padZero(monthDate.getMonth() + 1)}` // +1是因为月份是从0开始的
        // 如果你需要完整的日期字符串（这里只取年月），可以这样做：
        // monthDate.toISOString().slice(0, 7).replace('T', '-') // 输出格式如 "2023-09-"
    );
  }

  // 辅助函数，用于在数字前面补零
  function padZero(num) {
    return num.toString().padStart(2, '0');
  }

  // 返回月份数组
  return months;
}

const onOpenDialog = (data = null) => {
  // widgetFormDialogRef.value.onShowModel(data)
  router.push({name: 'EditProgram', params: {id: data?.id || 'create'}})
}

const onDelete = (data) => {
  TemplateApi.deleteTemplate(data.id).then(() => {
    const index = table.data.findIndex(item => item.id === data.id);
    table.data.splice(index, 1)
    ElMessage.success({
      message: '删除成功',
      showClose: true
    })
  })
}

const onEditCallback = (data) => {
  const index = table.data.findIndex(item => item.id === data.id);
  if (index < 0) {
    table.data.unshift(data)
  } else {
    table.data.splice(index, 1, data)
  }
}

const onPageChange = (pageIndex: number) => {
  if (pageIndex != table.paging.pageIndex) {
    getListData(pageIndex);
  }
}

</script>
<style scoped lang="scss">
  .yy-system-template_list {
      height: 100%;
      &-item {
        width: 20%;
        display: inline-flex;
        flex-direction: column;
        margin: 5px 5px;
        cursor: pointer;
        &-content {
          width: 100%;
          height: 0;
          padding-bottom: 50%;
          position: relative;
        }
      }
  }
</style>